<template>
    <div class="search"> 

        <!-- 搜索栏 -->
        <form action="/">
            <van-search
                v-model="searchText"
                show-action
                placeholder="请输入搜索关键词"
                @search="onSearch(searchText)"
                @cancel="$router.back()"
                @focus="isResultShow = false"
            />
        </form>
        <!-- 搜索结果 -->
        <search-result v-if="isResultShow " :searchtext = "searchText"> </search-result>
        <!-- 联想简易 -->
        <search-suggestions v-else-if="searchText" :searchtext = "searchText" @search="onSearch"> </search-suggestions>
        <!-- 历史记录 -->
        <search-history v-else
        :search-history= "SearchHistories"
        @search="onSearch"
        @clear-history="SearchHistories = $event"
        > </search-history>
    </div>
</template>
<script>
import SearchSuggestions from '@/views/search/components/search-suggestions'
import SearchHistory from '@/views/search/components/search-history'
import SearchResult from '@/views/search/components/search-result'
import { setItem,getItem } from '@/utils/storage'


export default {
 name: 'Search',
 data() {
     return {
        //  搜索的文字
         searchText: '',
        //  搜索结果
        isResultShow: false,
        //搜索历史记录
        SearchHistories: getItem('search-history') || []
     }
 },
 components: {
     SearchSuggestions,
     SearchHistory,
     SearchResult
 },
 methods: {
    //  确定搜索时触发
     onSearch(searchText){
         //控制搜索结果的显示
         this.searchText = searchText
         //填入搜索历史记录
         const index = this.SearchHistories.indexOf(searchText)
        //等于-1说明重复了  删除
         if(index !== -1){
             this.SearchHistories.splice(index,1)
         }
         this.SearchHistories.unshift(searchText)
 
         //存储到本地存储
            setItem('search-history',this.SearchHistories)
         //控制搜索模块的显示与隐藏
         this.isResultShow = true
     },
 },
  watch: {
      //监视历史记录
     SearchHistories(){
         //统一在这里本地话
        setItem('search-history',this.SearchHistories)
     }
 }
}
</script>
<style lang="less" scoped>

</style>